package service

import (
	"encoding/json"
	"errors"
	"fmt"
	"math/rand"
	constant "rongyy/src/constants"
	"rongyy/src/middlewares"
	"rongyy/src/models"
	"strconv"
	"time"
)

type InPatientService struct {
}

func (op *InPatientService) GetIPAdmInfoSer(req *models.Req5001Params) (*models.Resp5001, error) {
	data, err := (&HisService{}).GetIPAdmInfo(req)
	if data.ResultCode != "0" {
		return nil, fmt.Errorf(data.ResultMsg)
	}
	return data, err
}

func (op *InPatientService) IpDepositConfirm(req *models.ReqIpDeposit) (*models.Resp5002, error) {
	order, has, err := (&models.IpDepositModel{}).FindByOrderSn(req.OrderSn)
	if !has {
		return nil, fmt.Errorf("订单不存在")
	}
	if order.Status != "pending" || order.PayStatus != "paying" {
		return nil, fmt.Errorf("订单状态错误")
	}
	data, err := (&HisService{}).AddIPDeposit(req)
	if data.ResultCode != "0" {
		return nil, fmt.Errorf(data.ResultMsg)
	}
	ipd := &models.IpDepositModel{
		OrderSn:        req.OrderSn,
		UpdatedBy:      req.UpdatedBy,
		SerialNo:       data.SerialNo,
		DepositBalance: data.DepositBalance,
		Status:         "confirm",
		PayStatus:      "paid",
	}
	err = ipd.Confirm()
	if err != nil {
		middlewares.Logger.Println("押金入库失败")
		return nil, fmt.Errorf(data.ResultMsg)
	}
	return data, err
}

func (op *InPatientService) GetIPDepRecordSer(req *models.ReqIpDepositRecord) (*models.Resp5003, error) {
	data, err := (&HisService{}).GetIPDepRecord(req)
	if data.ResultCode != "0" {
		return nil, fmt.Errorf(data.ResultMsg)
	}
	return data, err
}

func (op *InPatientService) GetIPRegInfoSer(req *models.Req5010Params) (*models.Resp5010, error) {
	data, err := (&HisService{}).GetIPRegInfo(req)
	if data.ResultCode != "0" {
		return nil, fmt.Errorf(data.ResultMsg)
	}
	return data, err
}

//
//func (op *InPatientService) GetFeeList(req *models.Req11003Params) (*models.Resp11003, error) {
//	var requestXml helper.XmlString
//	_ = *requestXml.FeeListBeginXml("11003").
//		Xml("CardNo", req.CardNo).
//		Xml("CardType", req.CardType).
//		Xml("CardTypeCode", "").
//		Xml("StartDate", req.StartDate).
//		Xml("EndDate", req.EndDate).
//		Xml("CurrentIH", req.CurrentIH).
//		Xml("AdmType", req.AdmType).
//		Xml("IsApp", "").
//		Xml("AppMethodCode", req.AppMethodCode).
//		Xml("HospCode", "").
//		Xml("LocCode", req.LocCode).
//		Xml("DocCode", "").
//		Xml("WardCode", "").
//		Xml("ClientType", "").
//		Xml("Count", req.Count).
//		Xml("Page", req.Page).
//		Xml("PatientName", "").
//		Xml("RowId", "").
//		FeeListEndXml()
//
//	middlewares.Logger.Println("get IP Fee List xml ", requestXml)
//	data, err := helper.PostHisFeeList(string(requestXml))
//	//middlewares.Logger.Println("get IP Fee List result ==============================", result)
//	if err != nil {
//		return nil, err
//	}
//
//	//data := &models.Resp11003{}
//	//err = xml.Unmarshal([]byte(result.Response), data)
//	//if err != nil {
//	//	middlewares.Logger.Println("Unmarshal Resp11003 failed ", err)
//	//	return nil, err
//	//}
//	//data.Req = string(requestXml)
//	//data.Resp = result.BodyFee.MiRespFee.MiResultFee
//	if err != nil {
//		middlewares.Logger.Println("read response body failed", err)
//		return nil, err
//	}
//	if err != nil {
//		middlewares.Logger.Println("read response body failed", err)
//		return nil, err
//	}
//	result := &models.Resp11003{}
//	err = xml.Unmarshal([]byte(data.Body), result)
//	if err != nil {
//		middlewares.Logger.Println("Unmarshal response body failed", err)
//		return nil, err
//	}
//
//	return result, nil
//}

func (op *InPatientService) IPRegister(req *models.Req5011Params) (*models.Resp5011, error) {
	data, err := (&HisService{}).IPRegister(req)
	if data.ResultCode != "0" {
		return nil, fmt.Errorf(data.ResultMsg)
	}
	return data, err
}

func (op *InPatientService) InpatientInfo(req *models.Req11003Params) (*models.Resp11003, error) {
	data, err := (&HisService{}).InpatientInfo(req)
	if data.ResultCode != "0" {
		return nil, fmt.Errorf(data.ResultMsg)
	}
	return data, err
}
func (op *InPatientService) GetFeeList(req *models.Req11003Params) (*models.Resp11003, error) {
	data, err := (&HisService{}).GetFeeList(req)
	if data.ResultCode != "0" {
		return nil, fmt.Errorf(data.ResultMsg)
	}
	return data, err
}

func (op *InPatientService) GetFeeDetail(req *models.Req21001Params) (*models.Resp21001, error) {
	data, err := (&HisService{}).GetFeeListDetail(req)
	if data.ResultCode != "0" {
		return nil, fmt.Errorf(data.ResultMsg)
	}
	return data, err
}

func (op *InPatientService) GetFeeListDetail(req *models.ReqFeeDaily) (*models.RespFeeDaily, error) {
	data, err := (&HisService{}).GetFeeDaily(req)
	if data.ResultCode != "0" {
		return nil, fmt.Errorf(data.ResultMsg)
	}
	return data, err
}

func (op *InPatientService) BindBankCard(req *models.ReqBindBank) (*models.RespBindBankCard, error) {
	data, err := (&HisService{}).BindBankCard(req)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return nil, err
	}
	d := &models.RespBindBankCard{}
	err = json.Unmarshal(data, d)
	if err != nil {
		middlewares.Logger.Println("Unmarshal Resp32004 failed ", err)
		return nil, err
	}
	middlewares.Logger.Println("Unmarshal resp3013 failed ", data)
	return d, nil
}

func (op *InPatientService) UnBindBankCard(req *models.ReqUnBindBank) (*models.RespBindBankCard, error) {
	data, err := (&HisService{}).UnbindBankCard(req)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return nil, err
	}
	d := &models.RespBindBankCard{}
	err = json.Unmarshal(data, d)
	if err != nil {
		middlewares.Logger.Println("Unmarshal Resp32004 failed ", err)
		return nil, err
	}
	middlewares.Logger.Println("Unmarshal resp3013 failed ", data)
	return d, nil
}

func (pc *InPatientService) Pay(req *models.IpDepositModel, ip string) (*models.PaymentRespData, string, error) {
	//data, has, err := (&models.IpDepositModel{}).FindByOrderSn(req.OrderSn)
	//if has {
	//	return nil, "", errors.New("订单不存在")
	//}
	//if has && data.PayStatus == "paid" && data.Status == "confirm" {
	//	return nil, "", errors.New("订单状态错误")
	//}
	rand.Seed(time.Now().UnixNano())
	t := rand.Intn(10000)
	ts := strconv.FormatInt(time.Now().UnixMicro(), 10)
	orderSn := "I" + ts + strconv.Itoa(t)
	fee, err := strconv.ParseFloat(req.Fee, 10)
	reqPay := &models.PaymentReq{
		MerchantId: constant.MerchantId,
		Desc:       req.AdmId,
		PayStatus:  "unpaid",
		OutTradeNo: orderSn,
		TotalFee:   fee,
		ClientIp:   ip,
		BusiType:   "ip",
		OrderSn:    orderSn,
		PayWay:     constant.PayWay,
		OpenId:     req.Openid,
	}
	payResp, err := (&PaymentService{}).Pay(reqPay)
	middlewares.Logger.Println("Unmarshal resp3013 failed ", payResp)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return nil, "", err
	}
	if payResp.ERRCODE != "000000" {
		return nil, "", errors.New(payResp.ERRMSG)
	}
	//请求支付成功,入库
	reg := &models.IpDepositModel{
		AdmId:       req.AdmId,
		Fee:         req.Fee,
		PatientId:   req.PatientId,
		PatientName: req.PatientName,
		OrderSn:     orderSn,
		Status:      "pending",
		PayStatus:   "paying",
		Openid:      req.Openid,
	}
	err = reg.Create(reg)
	if err != nil {
		middlewares.Logger.Println("住院押金支付中入库错误 failed ", err)
		return nil, "", err
	}
	return payResp, orderSn, err
}
